import { getToken, setToken, removeToken } from '../../utils/auth'

import { login, getUser } from '../../api/user'

const user = {
  state: {
    token: getToken(),
    name: '11',
    roles: []
  },
  mutations: {
    SET_TOKEN: (state, name) => {
      state.token = name
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },
  actions: {
    setName ({ commit }, value) {
      commit('SET_NAME', '名称')
    },

    // 登陆
    loginFun ({ commit }, form) {
      return new Promise((resolve, reject) => {
        login(form).then((res) => {
          commit('SET_TOKEN', res.token)
          setToken(res.token)
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    },

    // 获取用户信息
    getUserInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getUser().then(res => {
          commit('SET_ROLES', res.roles)
          resolve(res.roles)
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 退出
    signOut () {
      return new Promise((resolve, reject) => {
        removeToken()
        resolve(200)
      })
    }
  }
}

export default user
